<template>
	<!-- 列表 -->
	<swiper class="home-swiper" @change="changeSwiper" :current="activeIndex">
		<swiper-item class="swiper-item" v-for="(item,index) in tabData" :key="index">
			<listItem :list="listCatchData[index]" @loadmore="loadmore" :load="load[index]">{{index}}</listItem>
		</swiper-item>
	</swiper>
</template>

<script>
	import listItem from "@/components/list/listItem.vue";

	export default {
		name: "list",
		components: {
			listItem
		},
		props: {
			// 由父组件传入
			tabData: {
				type: Array,
				default () {
					return []
				}
			},
			// 当前第几项
			activeIndex: {
				type: Number,
				default: 0
			}
		},
		data() {
			return {
				// list: [],
				listCatchData: {},
				load:{},
				pageSize:5
			};
		},
		watch: {
			tabData(newVal) {
				// 当数据为空时，返回
				if (newVal.len === 0) return;
				// 执行-获取文章列表数据函数
				this.getList(this.activeIndex);
			}
		},
		// onLoad 在页面，created 在组件
		created() {
			// TODO tabData 还没有赋值
			// this.getList(0);
		},
		methods: {
			// 改变-文章swiper的index时，发送事件changeSwiper
			changeSwiper(e) {
				const {
					current
				} = e.detail;
				// console.log(e);
				// console.log('current=>', current);
				// console.log('changeSwiper=>', this.tabData[current].name);

				this.$emit('changeSwiper', current);
				// TODO 当数据不存在或者长度是0的情况下，才取请求数据
				if (!this.listCatchData[current] || this.listCatchData[current].length === 0) {
					this.getList(current);
				}
			},
			// 获取-文章列表数据
			getList(current) {
				if(!this.load[current]){
					this.load[current] = {
						page:1,
						loading:"loading"
					}
				}
				
				this.$api.get_list({
						name: this.tabData[current].name,
						page:this.load[current].page,
						pageSize:this.pageSize
					})
					.then(res => {
						console.log('获取-文章列表数据=>', res);
						const {
							data
						} = res;
						console.log('请求数据：', data);
						
						if(data.length === 0 ) {
							let oldLoad = {};
							oldLoad.loading = 'noMore';
							oldLoad.page = this.load[current].page;
							this.$set(this.load,current,oldLoad);
							// 强制渲染页面
							this.$forceUpdate();
							return;
						}
						
						
						let oldListData = this.listCatchData[current] || [];
						oldListData.push(...data)
						// console.log('this.listCatchData=>',this.listCatchData);
						// console.log('current=>',current);
						// !!!通知页面，数据发生了变化，要去刷新一下
						// 数据懒加载
						this.$set(this.listCatchData, current, oldListData);
					})
			},
			// 上拉加载更多
			loadmore(){
				if(this.load[this.activeIndex].loading === 'noMore') return;
				console.log('触发上啦');
				this.load[this.activeIndex].page++;
				this.getList(this.activeIndex);
			}
		}
	}
</script>

<style lang="scss">
	.home-swiper {
		height: 100%;

		.swiper-item {
			height: 100%;
			overflow: hidden;

			.listScroll {
				height: 100%;
			}
		}
	}
</style>
